﻿using UnityEditor;
using UnityEngine;

namespace CWM.Skinn
{
    public static partial class SkinnContextCommands
    {
        [CtxMenuItem("Renderer/Mesh/Normals/Recalculate/Smoothed", "Experimental Smoothed Unity Normals " + "Only works with meshes that have one sub-mesh.", ContextRequirements.SingleItem, 0)]
        public static void SkinnedMeshRecalculateNormalsSmoothed()
        {
            foreach (var item in SkinnContext.GetContextItems())
            {
                var context = item.GetComponent<Renderer>();
                if (SkinnEx.IsNullOrNotInAScene(context)) continue;
                if (!SkinnEx.HasMinimumRequirements(context)) continue;
                if (context.GetComponent<MeshFilter>()) Undo.RegisterCompleteObjectUndo(context.GetComponent<MeshFilter>(), "Recalculate Normals");
                else Undo.RegisterCompleteObjectUndo(context, "Recalculate Normals");
                Mesh mesh = context.GetSharedMesh().Clone() as Mesh;
                mesh.normals = mesh.GetNormalsSmoothed();
                context.SetSharedMesh(mesh);
            }

            SkinnContext.Finished();
        }


        [CtxMenuItem("Renderer/Mesh/Normals/Recalculate/Unity", "Uses Unity's RecalculateNormals function. " +
            "Imported Meshes sometimes don't share all vertices." +
            " For example, a vertex at a UV seam is split into two vertices," +
            " so the RecalculateNormals function creates normals that are not smooth at the UV seam." +
            "Note that RecalculateNormals does not generate tangents automatically, so bump-map Shaders do not work with the Mesh after calling RecalculateNormals.However, you can provide your own tangents."
            , 0)]
        public static void SkinnedMeshRecalculateNormals()
        {
            foreach (var item in SkinnContext.GetContextItems())
            {
                var context = item.GetComponent<Renderer>();
                if (SkinnEx.IsNullOrNotInAScene(context)) continue;
                if (!SkinnEx.HasMinimumRequirements(context)) continue;
                if(context.GetComponent<MeshFilter>()) Undo.RegisterCompleteObjectUndo(context.GetComponent<MeshFilter>(), "Recalculate Normals");
                else Undo.RegisterCompleteObjectUndo(context, "Recalculate Normals");
                Mesh mesh = context.GetSharedMesh().Clone() as Mesh;
                mesh.normals = mesh.GetNormalsRecalculated();
                context.SetSharedMesh(mesh);
            }

            SkinnContext.Finished();
        }
    }
}